from django import forms
from django.shortcuts import render, redirect

from web import models
from utils.link import filter_reverse
from utils.bootstrap import BootStrapForm


class LevelModelForm(BootStrapForm, forms.ModelForm):
    # xxx = forms.CharField() 自定义字段
    # title = forms.CharField(label='提标')  重写title字段
    class Meta:
        model = models.Level
        fields = ['title', 'discount']
        # fields = '__all__' 根据表结构生成所有字段
        # exclude = ['active']   排除不需要的字段
        widgets = {'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '用户名'}),
                   'discount': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '用户名'})}

    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     for field in self.fields.items():
    #         field.widget.attrs['class'] += ' form-control'
    #         field.widget.attrs['placeholder'] = f'请输入{field.label}'


def level_list(request):
    queryset = models.Level.objects.filter(active=1)
    return render(request, 'level_list.html', {'queryset': queryset})


def level_add(request):
    if request.method == 'GET':
        form = LevelModelForm()
        return render(request, 'form.html', {'form': form})

    # 新增数据
    form = LevelModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})

    # {'title':'xxx', 'discount':'xx'}
    form.save()
    return redirect('level_list')


def level_edit(request, pk):
    #  获取要修改的对象
    level_object = models.Level.objects.filter(id=pk, active=1).first()
    if request.method == 'GET':
        form = LevelModelForm(instance=level_object)
        return render(request, 'form.html', {'form': form})

    # instance=level_object 更新数据
    form = LevelModelForm(data=request.POST, instance=level_object)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})

    # form.instance.discount = 0 假设输入为空，则不会更新，需要手动赋值
    form.save()

    return redirect(filter_reverse(request, 'level_list'))


def level_delete(request, pk):
    """级别删除"""

    if not models.Customer.objects.filter(level_id=pk).exists():
        level_object = models.Level.objects.filter(id=pk).update(active=0)
    # else:
    #     models.Customer.objects.filter(level_id=pk).update(level_id=None)
    return redirect('level_list')
